package org.supercall.controller.sys;

import com.alibaba.fastjson.JSON;
import com.google.gson.Gson;
import org.apache.commons.lang.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.supercall.common.CommonUtility;
import org.supercall.dao.SysConfigMapper;
import org.supercall.dao.SysMenuMapper;
import org.supercall.domainModel.MenuModel;
import org.supercall.models.SysConfig;
import org.supercall.models.SysConfigExample;
import org.supercall.models.SysMenu;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by kira on 16/8/2.
 */
@RequestMapping("/admin/common")
@RestController
public class CommonController {
    @Resource
    SysMenuMapper sysMenuMapper;

    @Resource
    SysConfigMapper sysConfigMapper;

    /**
     * 加载表单配置信息
     *
     * @param uid
     * @param id
     * @return
     * @throws ClassNotFoundException
     * @throws NoSuchMethodException
     * @throws InvocationTargetException
     * @throws IllegalAccessException
     */
    @RequestMapping(value = "/loadConfig", method = RequestMethod.GET)
    @ResponseBody
    @CrossOrigin
    public SysConfig loadConfig(String uid, String id) throws Exception{
        SysConfigExample configExample = new SysConfigExample();
        configExample.createCriteria().andUidEqualTo(uid);
        SysConfig configEntity = sysConfigMapper.selectByExampleWithBLOBs(configExample).get(0);

        HashMap<String, Object> metaMap = new Gson().fromJson(configEntity.getMetaconfig(), HashMap.class);
        List<Map<String, Object>> formConfigs = (List<Map<String, Object>>) metaMap.get("formConfigs");
        for (Map<String, Object> formConfig : formConfigs) {
            if (formConfig.get("inputType").equals("selector")) {
                Object dataSourceClass = Class.forName(String.valueOf(formConfig.get("dataSourcePluginName"))).newInstance();
                String dataSource = JSON.toJSON(dataSourceClass.getClass().getDeclaredMethod(String.valueOf(formConfig.get("dataSourcePlginFunction"))).invoke(dataSourceClass)).toString();
                formConfig.put("datasource", dataSource);
            }
        }

        //编辑模式下把值填入Value,供前端绑定
        if (StringUtils.isNotBlank(id)) {
            Object object = CommonUtility.applicationContext.getBean(Class.forName(String.valueOf(metaMap.get("entityName"))));

            Object entity = object.getClass().getMethod("selectByPrimaryKey", Integer.class).invoke(object, Integer.valueOf(id));
            for (Map<String, Object> formConfig : formConfigs) {
                formConfig.put("value", entity.getClass().getMethod("get" + StringUtils.capitalize(String.valueOf(formConfig.get("key")))).invoke(entity));
            }
        }
        String json = JSON.toJSON(metaMap).toString();
        configEntity.setMetaconfig(json);

        return configEntity;
    }

    /**
     * 加载菜单信息
     *
     * @param request
     * @return
     * @throws ClassNotFoundException
     */
    @RequestMapping(value = "/loadMenu", method = RequestMethod.GET)
    @ResponseBody
    @CrossOrigin
    List<MenuModel> index(
            HttpServletRequest request) throws ClassNotFoundException {
        List<SysMenu> menus = sysMenuMapper.selectByExample(null);
        List<MenuModel> menuModelList = new ArrayList<>();
        for (SysMenu menu : menus) {
            if (menu.getParentid() == null) {
                List<MenuModel> childrens = new ArrayList<MenuModel>();
                MenuModel entity = new MenuModel(menu.getName(), menu.getUrls() + "/" + menu.getName(), childrens, "", menu.getIcons());
                for (SysMenu sysMenu : menus) {
                    if (menu.getId().equals(sysMenu.getParentid())) {
                        MenuModel child = new MenuModel(sysMenu.getName(), sysMenu.getUrls() + "/" + sysMenu.getName(), null, "", sysMenu.getIcons());
                        childrens.add(child);
                    }
                }
                menuModelList.add(entity);
            }
        }
        return menuModelList;
    }

}
